package com.wenlin.myproduction.widget;

import android.animation.ValueAnimator;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Rect;
import android.text.TextPaint;
import android.util.AttributeSet;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.AccelerateDecelerateInterpolator;

import androidx.annotation.ColorInt;
import androidx.annotation.Nullable;

import com.wenlin.myproduction.R;

/**
 * @author cwl
 * @desc PK礼物进度条
 * @Email 377979485@qq.com
 * @time 2023/7/10 15:05
 */
public class PKProgressView extends View {
    private final float MARGIN = dpToPx(10);//边距
    private final float PROGRESS_MARGIN = dpToPx(30);//进度条边界的外边距
    private Bitmap bitmap;
    private Rect rect;
    private Paint paint;
    private TextPaint textPaint;
    @ColorInt
    private int colorLeft;//左侧颜色
    @ColorInt
    private int colorRight;
    private long totalLeft;//左侧总额
    private long totalRight;
    private String strLeft, strRight;
    private ValueAnimator animator;
    private float valueFloat;

    public PKProgressView(Context context) {
        this(context, null);
    }

    public PKProgressView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        try {
            TypedArray typedArray = context.obtainStyledAttributes(R.styleable.PKProgressView);
            colorLeft = typedArray.getColor(R.styleable.PKProgressView_pkpv_leftColor, Color.parseColor("#FF189EFF"));
            colorRight = typedArray.getColor(R.styleable.PKProgressView_pkpv_rightColor, Color.parseColor("#FFFF2B77"));
            typedArray.recycle();
        } catch (Exception e) {
            e.printStackTrace();
        }
        init();
    }

    /**
     * 初始化
     */
    private void init() {
        paint = new Paint();
        paint.setAntiAlias(true);
        paint.setDither(true);
        paint.setStyle(Paint.Style.FILL_AND_STROKE);

        textPaint = new TextPaint();
        textPaint.setTextSize(dpToPx(18));
        textPaint.setColor(Color.WHITE);

        rect = new Rect();

        bitmap = BitmapFactory.decodeResource(getResources(), R.mipmap.live_pk_star);
    }

    /**
     * 初始化数据
     *
     * @param totalLeft  左侧总额
     * @param totalRight 右侧总额
     */
    public void setInitData(long totalLeft, long totalRight) {
        this.totalLeft = totalLeft;
        this.totalRight = totalRight;
        valueFloat = getTargetX();
        postInvalidate();//cwl 2023/7/13 13:18：用invalidate会出现valueFloat=0的情况。
    }

    /**
     * 加左侧值
     *
     * @param left 值
     */
    public void addLeft(long left) {
        totalLeft += left;
        startAnim(getTargetX());
    }

    /**
     * 加右侧值
     *
     * @param right 值
     */
    public void addRight(long right) {
        totalRight += right;
        startAnim(getTargetX());
    }

    /**
     * 获取左侧总额
     *
     * @return 所求
     */
    public long getTotalLeft() {
        return totalLeft;
    }

    /**
     * 获取右侧总额
     *
     * @return 所求
     */
    public long getTotalRight() {
        return totalRight;
    }

    /**
     * 处理数据，并开始动画
     */
    private float getTargetX() {
        int width = getWidth();
        if (width <= 0) {
            WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
            width = wm.getDefaultDisplay().getWidth();
        }
        float progressWidth = width - PROGRESS_MARGIN * 2;
        float targetX;
        if (totalLeft == 0 && totalRight == 0) {
            targetX = width / 2f;
        } else if (totalLeft == 0 && totalRight > 0) {
            targetX = PROGRESS_MARGIN;
        } else if (totalRight == 0 && totalLeft > 0) {
            targetX = width - PROGRESS_MARGIN;
        } else {
            float radio = totalLeft / (float) (totalLeft + totalRight);
            targetX = PROGRESS_MARGIN + progressWidth * radio;
        }
//        LogU.v("totalLeft = " + totalLeft + " totalRight = " + totalRight + " targetX = " + targetX);
        return targetX;
    }

    /**
     * 开始动画
     */
    private void startAnim(float targetX) {
        if (animator != null && animator.isRunning()) {
            animator.cancel();
            animator = null;
        }
        animator = ValueAnimator.ofFloat(valueFloat, targetX);
        animator.addUpdateListener(valueAnimator -> {
            valueFloat = (float) valueAnimator.getAnimatedValue();
            invalidate();
        });
        animator.setDuration(1000);
        animator.setInterpolator(new AccelerateDecelerateInterpolator());
        animator.start();
    }

    /**
     * 转化长度单位
     *
     * @param dp dp长度
     * @return 对应的px长度
     */
    private float dpToPx(float dp) {
        float scale = getResources().getDisplayMetrics().density;
        return dp * scale;
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        //画进度条
        paint.setColor(colorLeft);
        canvas.drawRoundRect(0, 0, valueFloat, getHeight(), 0, 0, paint);
        paint.setColor(colorRight);
        canvas.drawRoundRect(valueFloat, 0, getWidth(), getHeight(), 0, 0, paint);
        //画值
//        strLeft = String.valueOf(totalLeft);
//        textPaint.getTextBounds(strLeft, 0, strLeft.length(), rect);
//        canvas.drawText(strLeft, MARGIN, getHeight() / 2f + rect.height() / 2f, textPaint);
//        strRight = String.valueOf(totalRight);
//        textPaint.getTextBounds(strRight, 0, strRight.length(), rect);
//        canvas.drawText(strRight, getWidth() - MARGIN - rect.width(), getHeight() / 2f + rect.height() / 2f, textPaint);
        //画图片和竖线
        if (bitmap != null)
            canvas.drawBitmap(bitmap, valueFloat - bitmap.getWidth() / 2f, getHeight() / 2f - bitmap.getHeight() / 2f, paint);
        paint.setColor(Color.WHITE);
        canvas.drawRoundRect(valueFloat - 2, 0, valueFloat + 2, getHeight(), 0, 0, paint);
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (bitmap != null && !bitmap.isRecycled()) {
            bitmap.recycle();
            bitmap = null;
        }
    }
}
